package com.thread.chapter3;

import cn.hutool.core.thread.ThreadUtil;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
public class Demo3_1_6 extends Thread {

    private Object lock;

    //传参决定执行哪个方法
    private String execMethod = "";
    private String threadName = "";


    public Demo3_1_6(Object lock, String execMethod, String threadName) {
        this.lock = lock;
        this.execMethod = execMethod;
        this.threadName = threadName;
    }

    //等待方法
    public void methodA() {
        currentThread().setName(threadName);
        try {
            synchronized (lock) {
                System.out.println("线程--" + currentThread().getName() + "开始等待");
                lock.wait();
                System.out.println("线程--" + currentThread().getName() + "结束等待");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //唤醒方法,notify()一次只随机通知一个线程进行唤醒，多次调用notify()方法会随机将等待wait状态的线程进行唤醒
    public void methodB() {
        currentThread().setName(execMethod);
        try {
            synchronized (lock) {
                System.out.println("线程--" + currentThread().getName() + "开始唤醒");
                lock.notify();
                lock.notify();
                lock.notify();
                System.out.println("线程--" + currentThread().getName() + "结束唤醒");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        super.run();
        if ("A".equals(execMethod)) {
            methodA();
        } else if ("B".equals(execMethod)) {
            methodB();
        }
    }

    public static void main(String[] args) {
        Object lock = new Object();
        Demo3_1_6 a = new Demo3_1_6(lock, "A", "t1");
        a.start();
        Demo3_1_6 b = new Demo3_1_6(lock, "A", "t2");
        b.start();
        Demo3_1_6 c = new Demo3_1_6(lock, "A", "t3");
        c.start();

        ThreadUtil.sleep(2000);
        Demo3_1_6 d = new Demo3_1_6(lock, "B", "t4");
        d.start();

    }
}
